package com.aw.guiguzi.module.manager._files

import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.aw.baselib.base.AwMvpBindingActivity
import com.aw.baselib.constants.Extras
import com.aw.baselib.util.AwDataUtil
import com.aw.baselib.util.AwFileUtil
import com.aw.baselib.util.AwLog
import com.aw.baselib.util.AwRecyclerViewUtil
import com.aw.baselib.util.download.AwFileDownloadUtil
import com.aw.baselib.util.download.DownloadResBean
import com.aw.baselib.widgets.MySmartRefreshLayout
import com.aw.guiguzi.R
import com.aw.guiguzi.bean.FileItemBean
import com.aw.guiguzi.constants.MyConstant
import com.aw.guiguzi.databinding.ActivityManagerFileListBinding
import com.aw.guiguzi.module.manager._files.adapter.FileListAdapter
import com.aw.guiguzi.module.manager._files.presenters.FileListPresent
import com.aw.guiguzi.module.manager._files.views.FileListView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter.RequestLoadMoreListener
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.scwang.smartrefresh.layout.api.RefreshLayout

class FileListActivity : AwMvpBindingActivity<FileListPresent?, ActivityManagerFileListBinding?>(),
    FileListView.View, RequestLoadMoreListener {
    private var mAdapter: FileListAdapter? = null
    private var index = 1
    private var total = 0
    private var mList: MutableList<FileItemBean> = ArrayList()
    override fun createPresenter(): FileListPresent {
        return FileListPresent(this)
    }

    override fun getViewBinding(): ActivityManagerFileListBinding {
        return ActivityManagerFileListBinding.inflate(layoutInflater)
    }

    override fun initView() {
        super.initView()
        setToolbar("文件列表", null)
    }

    override fun initData() {
        super.initData()
        mAdapter = FileListAdapter()
        AwRecyclerViewUtil.setRecyclerViewLinearlayout(mActivity, binding?.rcvData, mAdapter, false)
        getData(true)
    }

    override fun initListener() {
        super.initListener()
        binding?.sflLayout?.setOnRefreshListener { refreshLayout: RefreshLayout? -> getData(true) }
        mAdapter!!.setOnLoadMoreListener(this, binding?.rcvData)
        mAdapter!!.setOnItemClickListener { adapter: BaseQuickAdapter<*, *>, view: View?, position: Int ->
            val itemBean = adapter.getItem(position) as FileItemBean?
        }
        mAdapter!!.setOnItemChildClickListener { adapter: BaseQuickAdapter<*, *>, view: View, position: Int ->
            val itemBean = adapter.getItem(position) as FileItemBean?
            when (view.id) {
                R.id.tv_toSee -> {
                    if (!itemBean!!.name!!.endsWith("txt")) {
                        showMsg("该类型文件不支持查阅")
                        return@setOnItemChildClickListener
                    }
                    downloadAndOpen(itemBean)
                }

                R.id.tv_toDel -> showDialogWithCancelDismiss("确认删除该文件么？") { v: View? ->
                    mPresenter!!.delFile(
                        itemBean!!.id
                    )
                }
            }
        }
    }

    private fun getData(needResetIndex: Boolean) {
        if (needResetIndex) {
            index = 1
            mList = ArrayList()
            mAdapter!!.notifyDataSetChanged()
        }
        mPresenter!!.getFileList(index)
    }

    override fun onLoadMoreRequested() {
        if (mList.size < total) {
            index++
            getData(false)
        } else {
            if (index == 1 && mList.size < MyConstant.COMMON_LIST_PAGE_LIMIT_LARGE) {
                mAdapter!!.loadMoreEnd(true)
            } else {
                mAdapter!!.loadMoreEnd()
            }
        }
    }

    private fun downloadAndOpen(bean: FileItemBean?) {
        showLoadingDialog()
        val downloadResBeanList: MutableList<DownloadResBean> = ArrayList()
        val downloadResBean = DownloadResBean()
        downloadResBean.fileName = bean!!.name
        downloadResBean.url = bean.url
        downloadResBeanList.add(downloadResBean)
        AwFileDownloadUtil.startDownload(
            downloadResBeanList,
            true,
            object : FileDownloadListener() {
                override fun pending(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    showLoadingDialog()
                }

                override fun progress(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {}
                override fun completed(task: BaseDownloadTask) {
                    dismissLoadingDialog()
                    toClass(FileBrowseActivity::class.java, false, Extras.params, downloadResBean)
                    //                boolean isSuccess = AwThirdAppJudgeUtil.toThirdApp(mActivity, downloadResBean.getPath());
//                if(!isSuccess) {
//                    showDialog("请先安装可阅读文本的应用软件");
//                }
                }

                override fun paused(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {}
                override fun error(task: BaseDownloadTask, e: Throwable) {
                    dismissLoadingDialog()
                    AwLog.d("===>download fail, e: " + e.message)
                    showDialog("文件下载失败")
                }

                override fun warn(task: BaseDownloadTask) {}
            })
    }

    override fun getFileListSuccess(total: Int, list: List<FileItemBean>) {
        this.total = total
        binding?.sflLayout?.finishRefresh()
        if (AwDataUtil.isEmpty(list)) {
            AwRecyclerViewUtil.resetView(mActivity, mAdapter, binding?.rcvData, index == 1)
            return
        }
        mList.addAll(list)
        mAdapter!!.addAllData(mList)
        mAdapter!!.loadMoreComplete()
        mAdapter!!.disableLoadMoreIfNotFullPage(binding?.rcvData)
        var allSize: Long = 0
        for (itemBean in list) {
            allSize = AwDataUtil.getLongValue(itemBean!!.size) + allSize
        }
        setText(binding?.tvAllFileSize, "大小（" + AwFileUtil.bytes2kb(allSize) + "）")
    }

    override fun getFileListFail(code: Int, msg: String?) {
        binding?.sflLayout?.finishRefresh()
        AwRecyclerViewUtil.resetView(mActivity, mAdapter, binding?.rcvData, index == 1)
    }

    override fun delFileSuccess() {
        showMsg("删除文件成功")
        getData(true)
    }
}